package com.wswy.wzcx.ui.activity.news

import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.SizeUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.model.news.NewsCategory
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.main.home.HomeNewsFragment
import kotlinx.android.synthetic.main.activity_result_news.*
import java.util.ArrayList
import kotlin.math.abs

class ResultNewsActivity : CBaseActivity() {

    companion object {
        private const val TAG = "ResultNewsActivity"

        private const val TYPE_NORMAL = 0
        private const val TYPE_CAR = 1
        private const val TYPE_PAY = 2

        fun startCarResult(context:Context,userCarInfo: UserCarInfo){

            context.startActivity(Intent(context,ResultNewsActivity::class.java).apply {
                putExtra(Constants.EXTRA_TYPE,TYPE_CAR)

                putExtra(Constants.EXTRA_USER_CAR_INFO,userCarInfo)

            })

        }


        fun startPaySuccess(context:Context){
            context.startActivity(Intent(context,ResultNewsActivity::class.java).apply {
                putExtra(Constants.EXTRA_TYPE,TYPE_PAY)

            })
        }

    }


    private lateinit var resultNewsViewModel: ResultNewsViewModel

    private  var showType:Int = -1

    private var currentUserCarInfo:UserCarInfo?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result_news)

        resultNewsViewModel = provideViewModel(ResultNewsViewModel::class.java)


        showType = intent?.getIntExtra(Constants.EXTRA_TYPE, TYPE_NORMAL)?:TYPE_NORMAL

        when(showType){
            TYPE_NORMAL -> {
                setAppTitle(getString(R.string.news))

                img_back?.setImageResource(R.drawable.btn_back_selector)

            }

            TYPE_CAR -> {
                intent?.getParcelableExtra<UserCarInfo>(Constants.EXTRA_USER_CAR_INFO)?.run {
                    currentUserCarInfo = this
                    showCarHint(this)
                }

            }

            TYPE_PAY -> {
                showPaySuccess()
            }
        }


        if (showType == TYPE_NORMAL){
            view_top_bg.background = ColorDrawable(Color.WHITE)
            appbar.visibility = View.GONE

        }else {

            val topResultBgDrawable = TopResultBgDrawable()
            view_top_bg.background = topResultBgDrawable

            val dp160 = SizeUtils.dp2px(160f).toFloat()

            appbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { p0, offset ->

                if (abs(offset) >= dp160) {
                    setAppTitle(getString(R.string.news))
                } else {
                    when (showType) {

                        TYPE_CAR -> {
                            currentUserCarInfo?.run {
                                setAppTitle(carNo)
                            }
                        }

                        TYPE_PAY -> {
                            setAppTitle("支付结果")
                        }
                    }

                }

                topResultBgDrawable.colorMask((abs(offset).toFloat() / dp160))

            })

        }


        resultNewsViewModel.loadCategory()

        resultNewsViewModel.getNewsCategoriesLiveData().observe(this, Observer {


            it?.run {
                if (isOk() && data != null){
                    showNewsCategory(data)
                }
            }

        })


    }


    private fun showCarHint(userCarInfo: UserCarInfo){
        setAppTitle(userCarInfo.carNo)

        tv_msg_title.text = "查询成功"
        tv_msg_content.text = "恭喜您没有未处理违章记录！"
        tv_other_hint.run {
            visibility = View.VISIBLE
            text = "我有现场罚单或裁决罚单？"
            setOnClickListener {
                RouterUtils.start(context,RPaths.fkdj);
            }
        }

    }

    private fun showPaySuccess(){
        setAppTitle("支付结果")

        tv_msg_title.text = getString(R.string.pay_success)
        tv_msg_content.text = "我们将尽快为您办理，预计在2-5个工作日内办理完成"
        tv_other_hint.run {
            visibility = View.GONE
        }
    }

    private fun showNewsCategory(data: List<NewsCategory>?) {
        if (data == null || data.isEmpty()) {
            return
        }

        val list = ArrayList<NewsCategory>(5)

        if (data.size < 5) {
            list.addAll(data)
        } else {
            list.addAll(data.subList(0, 5))
        }

        val arrays = arrayOfNulls<String>(list.size)
        var i = 0
        for (newsCategory in list) {
            arrays[i++] = newsCategory.name
        }

        for (array in arrays) {
            tabLayout.addTab(tabLayout.newTab().setText(array))
        }

        tabLayout.setupWithViewPager(vp_news)
        vp_news.offscreenPageLimit = 5

        vp_news.adapter = object : FragmentPagerAdapter(supportFragmentManager) {

            override fun getCount(): Int {
                return arrays.size
            }

            override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
                super.setPrimaryItem(container, position, `object`)

            }

            override fun getItem(position: Int): Fragment {
                return HomeNewsFragment.newInstance(list[position],0)
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return arrays[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                super.destroyItem(container, position, `object`)
            }
        }

        vp_news.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {

                StatTools.sendShow(applicationContext, StatisticsId.click_News_Type, list[position].type)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })

        indicator.setTabLayoutAndViewPager(tabLayout, vp_news)
        tabLayout.requestLayout()
    }

    override fun onClickBack(view: View) {
        super.onClickBack(view)
        if (showType != TYPE_NORMAL){
            overridePendingTransition(0,R.anim.anim_top_close)
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (showType != TYPE_NORMAL){
            overridePendingTransition(0,R.anim.anim_top_close)
        }
    }

}